package com.zqx.spmab.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zqx.spmab.commons.FileUploadBean;
import com.zqx.spmab.dao.AttachmentDao;
import com.zqx.spmab.pojo.domain.Attachment;
import com.zqx.spmab.pojo.form.AttachmentForm;
import com.zqx.spmab.pojo.query.AttachmentQuery;
import com.zqx.spmab.service.AttachmentService;
import com.zqx.spmab.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Zqx on 2018/4/24.
 */
@Service
public class AttachmentServiceImpl implements AttachmentService{

    @Autowired
    private AttachmentDao attachmentDao;
    @Value("${system.baseStoragePath}")
    private String winUploadPath;
    @Value("${system.linuxBaseStoragePath}")
    private String linuxUploadPath;
    @Value("${system.baseStorageTempPath}")
    private String winUploadTempPath;
    @Value("${system.linuxBaseStorageTempPath}")
    private String linuxUploadTempPath;

    private String getUploadPath() {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            return winUploadPath;
        } else {
            return linuxUploadPath;
        }
    }

    private String getUploadTempPath() {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            return winUploadTempPath;
        } else {
            return linuxUploadTempPath;
        }
    }

    /**
     * 文件上传
     */
    public String uploadFile(final MultipartFile file,final AttachmentForm form) throws Exception {
        byte[] bytes = file.getBytes();
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        SimpleDateFormat formatter = new SimpleDateFormat("/YYYYMM/YYYYMMDD/hhmmss-");
        String dateString = formatter.format(new Date());
        String path = dateString + UUID.randomUUID().toString().replaceAll("-", "");


        String targetPathNameWithoutSuffix = getUploadPath() + path; // 真实路径
        //创建目录
        if(!file.isEmpty())
        {
            File f = new File(targetPathNameWithoutSuffix);
            if(f.exists()) {

            } else {
                //  先创建文件所在的目录
                f.getParentFile().mkdirs();
            }
        }
        Path realpath = Paths.get(targetPathNameWithoutSuffix+"."+suffix);
        Files.write(realpath, bytes);

        String pathWithSuffix = path + "." + suffix;
        form.setAttachName(originalFilename);
        form.setFileType(suffix);
        form.setFileLength(Long.valueOf(file.getSize()));
        form.setFileUrl(pathWithSuffix);
        form.setFilePath(pathWithSuffix);
        attachmentDao.add(form);

        return form.getId();
    }
    /**
     * 文件上传--存放不改变文件名称
     */
    public String uploadFileOnOldName(final FileUploadBean uploadItem,final AttachmentForm form) throws Exception {
        if(form.getIsOne()!=null && form.getIsOne()){
            attachmentDao.deleteForOne(form);
        }
        String originalFilename = uploadItem.getFile().getOriginalFilename();
        String oldName = originalFilename.substring(0,originalFilename.indexOf("."));
        String suffix = FileUtil.getSuffix(originalFilename); // 后缀
        SimpleDateFormat formatter = new SimpleDateFormat("/YYYYMM/YYYYMMDD/hhmmss-");
        String dateString = formatter.format(new Date());
        String path = dateString + UUID.randomUUID().toString().replaceAll("-", "")+"/"+oldName; // 相对路径
        String targetPathNameWithoutSuffix = getUploadPath() + path; // 真实路径
        /**
         * （1）上传之前
         * （2）上传中
         * （3）上传后
         * */
        // 上传路径:/base路径/月份/日期/时间+随机数.后缀

        FileUtil.uploadFileSpringMVC(uploadItem.getFile(), targetPathNameWithoutSuffix);
        String pathWithSuffix = path + "." + suffix;
        form.setAttachName(originalFilename);
        form.setFileType(suffix);
        form.setFileLength(Long.valueOf(uploadItem.getFile().getSize()));
        form.setFileUrl(pathWithSuffix);
        form.setFilePath(pathWithSuffix);
        attachmentDao.add(form);
        return form.getId();
    }

    /**
     * 下载文件
     */
    public void download(final String id, final HttpServletResponse response) throws FileNotFoundException {
        try {
            Attachment attachment = attachmentDao.get(id);
            File file = new File(getUploadPath() + attachment.getFilePath());
            if (file.exists()) {
                BufferedImage image = ImageIO.read(file);
                if (image != null) {
                    response.setContentType("image/" + attachment.getFileType());
                    ImageIO.write(image, attachment.getFileType(), response.getOutputStream());
                } else {
                    FileUtil.download(file.getAbsolutePath(), attachment.getAttachName().replace("." + attachment.getFileType(), ""), response);
                }
            } else {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("系统错误或文件已被删除！请联系管理员！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询 Attachment
     */
    public List<Attachment> find(final AttachmentQuery query) {
        return attachmentDao.find(query);
    }

    /**
     * 分页查询 Attachment
     */
    public Page<Attachment> findByPage(final AttachmentQuery query) {
        PageHelper.startPage(query.getPage().intValue(), query.getLimit().intValue());
        return (Page<Attachment>) attachmentDao.find(query);
    }

    /**
     * 通过id得到一个 Attachment
     */
    public Attachment get(final String id) {
        return attachmentDao.get(id);
    }

    /**
     * 新增 Attachment
     */
    public void add(final AttachmentForm form) {
        attachmentDao.add(form);
    }


    /**
     * 修改 Attachment
     */
    public int update(final AttachmentForm form) {
        return attachmentDao.update(form);
    }

    /**
     * 删除一个 Attachment
     */
    public int delete(final String id) {
        return attachmentDao.delete(id);
    }

    /**
     * 修改是否可用
     */
    public int changeEnabled(final String id, final Integer enabled) {
        return attachmentDao.changeEnabled(id, enabled);
    }
}
